package one.stand.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.jmp.base.dto.ChatMsgSystemDto;
import com.jmp.chat.*;
import one.stand.advice.ResultEnum;
import one.stand.mapper.UserChatMapperExt;
import one.stand.mapper.UserMapperExt;
import one.stand.model.User;
import one.stand.model.UserChat;
import one.stand.service.ChatService;
import one.stand.service.user.UserAdminService;
import one.stand.util.AssertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class ChatServiceImpl implements ChatService {
    @Autowired
    private UserAdminService userAdminService;

    @Autowired
    private ChatClient chatClient;
    @Autowired
    private UserChatMapperExt userChatMapperExt;
    @Autowired
    private UserMapperExt userMapperExt;

    @Override
    @Async("asyncServiceExecutor")
    public void init() {
        PageHelper.startPage(1, 100);
        List<Integer> userIds = userMapperExt.selectChatNull();
        for (Integer userId : userIds) {
            get(userId);
        }
    }

    @Override
    public void save(Integer userId) {
        User user = userAdminService.getByUserId(userId);

        UserChat userChat = userChatMapperExt.selectByUserId(userId);
        if (Objects.nonNull(userChat) && user.getNickeName().equals(userChat.getNickName()) && user.getAvatarUrl().equals(userChat.getPhoto())) {
            return;
        }

        ChatSaveRequest savePo = ChatSaveRequest.builder()
                .userId(String.valueOf(user.getUserId()))
                .nickName(user.getNickeName())
                .pic(user.getAvatarUrl())
                .build();
        boolean saveFlag = chatClient.save(savePo);
        AssertUtil.isTrue(saveFlag, ResultEnum.FAIL);

        if (Objects.nonNull(userChat)) {
            UserChat userChatUpdate = new UserChat();
            userChatUpdate.setId(userChat.getId());
            userChatUpdate.setNickName(savePo.getNickName());
            userChatUpdate.setPhoto(savePo.getPic());
            userChatMapperExt.updateByPrimaryKeySelective(userChatUpdate);
        } else {
            userChat = new UserChat();
            userChat.setUserId(user.getUserId());
            userChat.setChatUserId(String.valueOf(user.getUserId()));
            userChat.setNickName(savePo.getNickName());
            userChat.setPhoto(savePo.getPic());
            userChatMapperExt.insertSelective(userChat);
        }
    }

    @Override
    @Async("asyncServiceExecutor")
    public void groupSystemMsg(String groupId, String content) {

        ChatGroupSystemMsgPo po = ChatGroupSystemMsgPo.builder()
                .groupId(groupId)
                .content(content)
                .build();
        chatClient.groupSystemMsg(po);
    }

    @Override
    @Async("asyncServiceExecutor")
    public void msgSystem(ChatMsgSystemDto request) {
        UserChat userChat = userChatMapperExt.selectByChatUserId(ID_SYS);
        MsgType msgType = MsgType.valueOf(request.getType());
        if (MsgType.TEXT.equals(msgType)) {//文本消息
            ChatSendmsgPo po = ChatSendmsgPo.builder()
                    .fromUser(userChat.getChatUserId())
                    .toUser(request.getToId())
                    .content(msgType.getText(request.getTextParams()))
                    .isCustom(false)
                    .build();
            po.setMsgContent(po.getContent());
            chatClient.sendmsg(po);
        } else {//自定义消息
            SysMsg sysMsg = SysMsg.builder()
                    .messageType(msgType.name())
                    .messageText(msgType.getText(request.getTextParams()))
                    .messageData(msgType.getData(request.getDataParams()))
                    .messageName(userChat.getNickName())
                    .messageUrl(userChat.getPhoto())
                    .build();
            ChatSendmsgPo po = ChatSendmsgPo.builder()
                    .fromUser(userChat.getChatUserId())
                    .toUser(request.getToId())
                    .content(JSON.toJSONString(sysMsg))
                    .msgContent(sysMsg.getMessageText())
                    .isCustom(true)
                    .build();
            chatClient.sendmsg(po);
        }
    }

    @Override
    public UserChat get(Integer userId) {
        UserChat userChat = userChatMapperExt.selectByUserId(userId);
        if (Objects.isNull(userChat)) {
            save(userId);
            userChat = userChatMapperExt.selectByUserId(userId);
        }
        return userChat;
    }
}
